﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
namespace Assignment2
{
    public static class Logger
    {
        //************************************************************************
        //*
        //*  Variables
        //*
        //************************************************************************

        private static StreamWriter writer;
        private static Mutex _mutex = new Mutex();

        //************************************************************************
        //*
        //*  Initialize
        //*
        //************************************************************************

        public static void create_log(String filename)
        {
            String path = Directory.GetCurrentDirectory();

            path += "\\" + filename;

            try
            {
                writer = new StreamWriter(path);
            }
            catch (Exception ex)
            {
                String message =
                    "Unable to open log file at path: " + path +
                    ".  Exception: " + ex.Message;
                Console.WriteLine(message);
            }

        }

        //************************************************************************
        //*
        //*  Log message
        //*
        //************************************************************************

        public static void log_message(String message)
        {
            try
            {
                _mutex.WaitOne();
                String log_message =
                    "[" + DateTime.Now.ToShortDateString() + ": " +
                    DateTime.Now.ToLongTimeString() +"] " + message;
                writer.WriteLine(log_message);
                _mutex.ReleaseMutex();
            }
            catch (Exception ex)
            {
                String exception_message =
                    "Unable to write to log file!\r\n" +
                    "Exception occured: " + ex.Message;
                Console.WriteLine(exception_message);
            }
        }

        //************************************************************************
        //*
        //*  Close log
        //*
        //************************************************************************

        public static void close_log()
        {
            try
            {
                writer.Close();
            }
            catch (Exception ex)
            {
                String exception_message =
                    "Exception occured while trying to close the log file: " + ex.Message;
                Console.WriteLine(exception_message);
            }
        }
    }
}
